package com.shijiwei.lifthelper.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.shijiwei.lifthelper.R;
import com.shijiwei.lifthelper.adapter.WeatherAdapter;
import com.shijiwei.lifthelper.bean.Weather;
import com.shijiwei.lifthelper.ui.CityManagerActivity;
import com.shijiwei.lifthelper.utils.UrlConstants;

import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by sjw on 2015/12/12.
 */
@ContentView(R.layout.fragment_weather)
public class WeatherFragment extends BaseFragment {

    @ViewInject(R.id.scrollView)
    private PullToRefreshScrollView scrollView;
    @ViewInject(R.id.gridview)
    private GridView gridView;
    @ViewInject(R.id.tv_weather)
    private TextView tvWeather;
    @ViewInject(R.id.tv_city)
    private TextView tvCity;
    @ViewInject(R.id.tv_week)
    private TextView tvWeek;
    @ViewInject(R.id.tv_date)
    private TextView tvDate;
    @ViewInject(R.id.tv_ditail)
    private TextView tvDtail;
    @ViewInject(R.id.tv_temperature)
    private TextView tvTemperature;
    @ViewInject(R.id.tv_quality)
    private TextView tvQuality;
    @ViewInject(R.id.iv_weather)
    private ImageView ivWeather;
    @ViewInject(R.id.iv_addcity)
    private ImageView ivAddCity;

    private List<String> cityNames;
    private String city = "";
    private String url;
    private Weather weather;
    private List<Weather.ResultEntity.DataEntity.WeatherEntity> list;
    private WeatherAdapter adapter;

    public static final int REQUEST_CITY = 1;
    private CityReceiver receiver;

    //定位相关
    private MapView mapView;
    private BaiduMap baiduMap;
    private LocationClient locationClient;
    private LocationClientOption clientOption;


    public static WeatherFragment newInstance() {

        Bundle args = new Bundle();

        WeatherFragment fragment = new WeatherFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void initView() {
        regist();
        scrollView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);

        scrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                getData(city);
            }
        });

    }

    @Override
    public void initData() {

        addListener();

        list = new ArrayList<>();
        adapter = new WeatherAdapter(list, getActivity());
        gridView.setAdapter(adapter);

        cityNames = new ArrayList<String>();
        location();
    }

    private void addListener() {
        ivAddCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), CityManagerActivity.class));
            }
        });
    }

    public void getData(String city) {
        try {
            city = URLEncoder.encode(city, "UTF-8");
            url = UrlConstants.WEATHER_URL_GET + city;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        x.http().get(new RequestParams(url), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(final String result) {
                if (!TextUtils.isEmpty(result)) {
                    weather = JSON.parseObject(result, Weather.class);

                    if (weather.getError_code() == 0) {
                        list.clear();
                        list.addAll(weather.getResult().getData().getWeather());
                        list.remove(0);
                        list.remove(list.size() - 1);
                        list.remove(list.size() - 1);
                        adapter.notifyDataSetChanged();

                        List<String> day = weather.getResult().getData().getWeather().get(0).getInfo().getDay();
                        List<String> night = weather.getResult().getData().getWeather().get(0).getInfo().getNight();
                        tvTemperature.setText(day.get(2)+ " - " + night.get(0)+"℃");
                        tvWeather.setText(day.get(1));
                        tvCity.setText(weather.getResult().getData().getRealtime().getCity_name());
                        tvWeek.setText("周"+weather.getResult().getData().getWeather().get(0).getWeek());
                        tvDate.setText(weather.getResult().getData().getRealtime().getDate());
                        judgeQuality(Integer.parseInt(weather.getResult().getData().getPm25().getPm25().getPm25()));
                        tvDtail.setText(weather.getResult().getData().getPm25().getPm25().getPm25()+"  >");
                        judgeWeatherIcon(day.get(1), ivWeather);
                    }else {
                        Toast.makeText(getActivity(), "网络异常,请求不到数据啊！！", Toast.LENGTH_SHORT).show();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getActivity(), "网络异常,请求不到数据啊！！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                scrollView.onRefreshComplete();
            }
        });
    }


    public void judgeQuality(int quality) {
        if (quality <= 50) {//优
            tvQuality.setText("空气质量  优");
        } else if (quality >= 51 && quality <= 100) {//良
            tvQuality.setText("空气质量  良");
        } else if (quality >= 101 && quality <= 150) {//轻度污染
            tvQuality.setText("空气质量  轻度污染");
        } else if (quality >= 151 && quality <= 200) {//中度污染
            tvQuality.setText("空气质量  中度污染");
        } else if (quality >= 201 && quality <= 300) {//重度污染
            tvQuality.setText("空气质量  重度污染");
        } else if (quality > 300) {//严重污染
            tvQuality.setText("空气质量  严重污染");
        }
    }

    public static void judgeWeatherIcon(String weather, ImageView icon) {
        if (weather.endsWith("雨")) {
            icon.setImageResource(R.mipmap.ic_yu);
            if (weather.endsWith("小雨")) {
                icon.setImageResource(R.mipmap.ic_xiaoyu);
            } else if (weather.endsWith("中雨")) {
                icon.setImageResource(R.mipmap.ic_zhongyu);
            } else if (weather.endsWith("大雨")) {
                icon.setImageResource(R.mipmap.ic_dayu);
            }
        } else if (weather.endsWith("雪")) {
            icon.setImageResource(R.mipmap.ic_xiaoxue);
            if (weather.endsWith("小雪")) {
                icon.setImageResource(R.mipmap.ic_xiaoxue);
            } else if (weather.endsWith("中雪")) {
                icon.setImageResource(R.mipmap.ic_zhongxue);
            } else if (weather.endsWith("大雪")) {
                icon.setImageResource(R.mipmap.ic_daxue);
            }

        } else if (weather.endsWith("云")) {
            icon.setImageResource(R.mipmap.ic_duoyun);
        } else if (weather.endsWith("晴")) {
            icon.setImageResource(R.mipmap.ic_qin);
        } else if (weather.endsWith("雾")) {
            icon.setImageResource(R.mipmap.ic_wu);
        } else if (weather.endsWith("霾")) {
            icon.setImageResource(R.mipmap.ic_wu);
        } else if (weather.endsWith("阴")) {
            icon.setImageResource(R.mipmap.ic_yin);
        } else if (weather.endsWith("冰雹")) {
            icon.setImageResource(R.mipmap.ic_ice);
        }
    }

    class CityReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            city = intent.getStringExtra("city");
            getData(city);
        }
    }

    //定位
    public void location() {
        mapView = new MapView(getActivity());
        baiduMap = mapView.getMap();
        baiduMap.setMyLocationEnabled(true);
        locationClient = new LocationClient(getActivity());
        clientOption = new LocationClientOption();
        clientOption.setOpenGps(true);
        clientOption.setCoorType("bd09ll");
        clientOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        clientOption.setIsNeedAddress(true);
        locationClient.setLocOption(clientOption);
        locationClient.start();
        locationClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                if (!TextUtils.isEmpty(bdLocation.getAddress().address)){
                    city = bdLocation.getCity().substring(0, bdLocation.getCity().lastIndexOf("市"));
                    LogUtil.d(city);
                String address = bdLocation.getAddress().address;
                if (address.contains("区")){
                    city = address.substring(address.lastIndexOf("市")+1,address.lastIndexOf("区"));
                }else if (address.contains("县")){
                    city = address.substring(address.lastIndexOf("市")+1,address.lastIndexOf("县"));
                }

                    getData(city);
                }

            }
        });
    }

    public void regist() {
        receiver = new CityReceiver();
        IntentFilter filter = new IntentFilter("com.shijiwei.lifthelper.ADDCITY");
        getActivity().registerReceiver(receiver, filter);
    }


    @Override
    public void onPause() {
        super.onPause();
        locationClient.stop();
    }

    @Override
    public void onStop() {
        super.onStop();
        locationClient.stop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiver);
        locationClient.stop();
    }
}
